﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameProtocol.DTO;
using LOLServer.Biz.Account.Interface;
using LOLServer.Cache;
using LOLServer.Cache.Interface;
using NetFrame;
using NetFrame.Util;
using NetFrame.Log;

namespace LOLServer.Biz.Impl
{
    /// <summary>
    /// 用户逻辑中的事务层
    /// </summary>
    public class AccountBiz : IAccountBiz
    {
        private IAccountCache mAc = CacheFactory.mAccountCache;
        /// <summary>
        /// 创建账户
        /// </summary>
        /// <param name="ut"></param>
        /// <param name="PassToken"></param>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public int CreateAccount(UserToken ut, string PassToken, ref int accountId)
        {
            string index = Utils.GetRandomString(6, true, false, false, false);
            accountId = index.ToInt();
            if (mAc.HasAccount(accountId))//如果账号存在
            {
                return 1;
            }
            else if (!mAc.YesPassToken(ut, PassToken))//如果验证码不正确
            {
                return 2;
            }
            mAc.AddAccount(accountId, PassToken);
            mAc.OnLine(ut, accountId);
            return 0;
        }
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="ut"></param>
        /// <param name="error"></param>
        public void DisConnect(UserToken ut, string error)
        {
            Logger.Info(string.Format("客户端下线:{0}", error));
            mAc.OffLine(ut);
        }

        public int GetAccountId(UserToken ut)
        {
            return mAc.GetAccountId(ut);
        }
        /// <summary>
        /// 握手处理
        /// </summary>
        /// <param name="ut"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public string HandShake(UserToken ut, string value)
        {
            string passToken = MD5String.GetMD5String(value).ToUpper();
            mAc.AddPassToken(ut, passToken);
            return passToken;
        }
        /// <summary>
        /// 账户登录
        /// </summary>
        /// <param name="ut"></param>
        /// <param name="AccountId"></param>
        /// <param name="PassToken"></param>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public int LoginAccount(UserToken ut, int AccountId,string PassToken, ref int accountId)
        {
            if (!mAc.HasAccount(AccountId))
            {
                return 1;
            }
            mAc.YesPassToken(ut, PassToken);
            mAc.AddAccount(AccountId, PassToken);
            mAc.OnLine(ut, AccountId);
            accountId = AccountId;
            return 0;
        }
    }
}
